package com.auerdi.ui.fragment.a_home;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.auerdi.R;
import com.auerdi.base.BaseMainFragment;
import com.auerdi.event.TabSelectedEvent;
import com.auerdi.ui.fragment.MainFragment;
import com.auerdi.ui.fragment.a_home.adapter.HomeRcAdapter;
import com.auerdi.ui.fragment.a_home.adapter.delegate.AisBanner;
import com.auerdi.ui.fragment.a_home.adapter.delegate.BisAct;
import com.auerdi.ui.fragment.a_home.adapter.delegate.CisReportPic;
import com.auerdi.ui.fragment.a_home.adapter.delegate.DisGoodLoveList;
import com.auerdi.ui.fragment.a_home.adapter.delegate.EisGoodWorldList;
import com.auerdi.ui.fragment.a_home.adapter.delegate.FisGoodLastList;
import com.auerdi.ui.fragment.a_home.adapter.items.HomeItemsBean;
import com.example.egghttp.EggLog.L;
import com.example.egghttp.RetrofitClient;
import com.example.egghttp.retrofit.AdService;
import com.example.egghttp.retrofit.beans.BOb;
import com.example.egghttp.retrofit.beans.banner.ActrepList;
import com.example.egghttp.retrofit.beans.banner.BannerList;
import com.example.egghttp.retrofit.beans.banner.GoodLoveList;
import com.example.egghttp.retrofit.beans.banner.HomeBanner;
import com.example.egghttp.retrofit.beans.banner.ReportsPic;
import com.example.egghttp.retrofit.beans.goods.Product;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import me.yokeyword.eventbusactivityscope.EventBusActivityScope;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by YoKeyword on 16/6/30.
 */
public class AdHomeTabFragment extends BaseMainFragment {

    Unbinder unbinder;
//    @BindView(R.id.toolbar)
//    Toolbar mToolbar;
    @BindView(R.id.refresh_layout)
    SwipeRefreshLayout mRefreshLayout;
    @BindView(R.id.crazy)
    RecyclerView crazyList;

    private int disFronTop = 0;
    private List<HomeItemsBean> mainHomeList = new ArrayList<>();

    public static AdHomeTabFragment newInstance() {
        Bundle args = new Bundle();
        AdHomeTabFragment fragment = new AdHomeTabFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

//        L.d("hcia", "onCreateView:");

        View view = inflater.inflate(R.layout.fragment_tab_home, container, false);
        unbinder = ButterKnife.bind(this, view);
        EventBusActivityScope.getDefault(_mActivity).register(this);

//        mToolbar.setTitle(R.string.home);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this.getContext(), 12, GridLayoutManager.VERTICAL, false) {


            @Override
            public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
                try {
                    //try catch一下
                    super.onLayoutChildren(recycler, state);
                } catch (IndexOutOfBoundsException e) {
                    L.d("hcia", "e:" + e);
                    e.printStackTrace();
                }

            }

        };


        crazyList.setLayoutManager(gridLayoutManager);
        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                //计算在哪个position时要显示1列数据，即columnCount / 1列 = 4格，即1列数据占满4格
                if (mainHomeList.get(position).getRouter().equals(DisGoodLoveList.class.getSimpleName())) {
                    return 12 / 3;
                }
                return 12;
            }
        });


        crazyList.setAdapter(new HomeRcAdapter(getActivity(), mainHomeList));


        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {

//                mainHomeList.clear();
//                requestData();
                mRefreshLayout.setRefreshing(false);


            }
        });


        return view;
    }

    private void requestData() {
        RetrofitClient.getClient().create(AdService.class).homebanner("", "")
                .subscribeOn(Schedulers.newThread())
                .observeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BOb<BannerList>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(BOb<BannerList> bannerListBOb) {
                        List<HomeBanner> banners = bannerListBOb.getBody().getHomeBanner_list();
                        HomeItemsBean tem = new HomeItemsBean<List<HomeBanner>>() {

                            @Override
                            public List<HomeBanner> getItem() {
                                return banners;
                            }

                            @Override
                            public String getRouter() {
                                return AisBanner.class.getSimpleName();

                            }
                        };


                        mainHomeList.add(tem);
                        Collections.sort(mainHomeList, new Comparator<HomeItemsBean>() {
                            public int compare(HomeItemsBean arg0, HomeItemsBean arg1) {

                                return arg0.getRouter().compareTo(arg1.getRouter());
                            }
                        });
                        crazyList.getAdapter().notifyDataSetChanged();


                    }
                });


        RetrofitClient.getClient().create(AdService.class).actRep()
                .subscribeOn(Schedulers.newThread())
                .observeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BOb<ActrepList>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        L.d("hcia", "e:" + e);

                    }

                    @Override
                    public void onNext(BOb<ActrepList> bannerListBOb) {
                        List<HomeBanner> banners = bannerListBOb.getBody().getActrep();
                        HomeItemsBean tem = new HomeItemsBean<List<HomeBanner>>() {

                            @Override
                            public List<HomeBanner> getItem() {
                                return banners;
                            }

                            @Override
                            public String getRouter() {
                                return BisAct.class.getSimpleName();
                            }
                        };


                        mainHomeList.add(tem);
                        Collections.sort(mainHomeList, (arg0, arg1) -> arg0.getRouter().compareTo(arg1.getRouter()));
                        crazyList.getAdapter().notifyDataSetChanged();


                    }
                });

        RetrofitClient.getClient().create(AdService.class).reportPic()
                .subscribeOn(Schedulers.newThread())
                .observeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BOb<ReportsPic>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        L.d("hcia", "e:" + e);

                    }

                    @Override
                    public void onNext(BOb<ReportsPic> bannerListBOb) {
                        HomeBanner repotAct = bannerListBOb.getBody().getReports();
                        HomeItemsBean tem = new HomeItemsBean<HomeBanner>() {
                            @Override
                            public HomeBanner getItem() {
                                return repotAct;
                            }

                            @Override
                            public String getRouter() {
                                return CisReportPic.class.getSimpleName();
                            }
                        };


                        mainHomeList.add(tem);
                        Collections.sort(mainHomeList, (arg0, arg1) -> arg0.getRouter().compareTo(arg1.getRouter()));
                        crazyList.getAdapter().notifyDataSetChanged();


                    }
                });


        RetrofitClient.getClient().create(AdService.class).goodLoveList()//這週我最愛
                .subscribeOn(Schedulers.newThread())
                .observeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BOb<GoodLoveList>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        L.d("hcia", "e:" + e);

                    }

                    @Override
                    public void onNext(BOb<GoodLoveList> bannerListBOb) {


                        List<Product> ddd = bannerListBOb.getBody().getProLists();
                        HomeItemsBean header = new HomeItemsBean<String>() {

                            @Override
                            public String getItem() {
                                return "— 这 周 我 最 爱 —";
                            }

                            @Override
                            public String getRouter() {
                                return "DisGoodLoveAHeader";

                            }
                        };

                        mainHomeList.add(header);

                        for (Product product : ddd) {


                            HomeItemsBean tem = new HomeItemsBean<Product>() {

                                @Override
                                public Product getItem() {
                                    return product;
                                }

                                @Override
                                public String getRouter() {
                                    return DisGoodLoveList.class.getSimpleName();

                                }
                            };
                            mainHomeList.add(tem);
                        }


                        Collections.sort(mainHomeList, (arg0, arg1) -> arg0.getRouter().compareTo(arg1.getRouter()));
                        crazyList.getAdapter().notifyDataSetChanged();


                    }
                });


        RetrofitClient.getClient().create(AdService.class).goodWorldsList()
                .subscribeOn(Schedulers.newThread())
                .observeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BOb<GoodLoveList>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        L.d("hcia", "e:" + e);

                    }

                    @Override
                    public void onNext(BOb<GoodLoveList> bannerListBOb) {


                        List<Product> GoodLoveLists = bannerListBOb.getBody().getProLists();
                        HomeItemsBean header = new HomeItemsBean<String>() {

                            @Override
                            public String getItem() {
                                return "— 团 一 个 世 界 —";
                            }

                            @Override
                            public String getRouter() {
                                return "EisGoodWorldAHeader";

                            }
                        };
                        mainHomeList.add(header);
                        for (Product product : GoodLoveLists) {
                            HomeItemsBean tem = new HomeItemsBean<Product>() {

                                @Override
                                public Product getItem() {
                                    return product;
                                }

                                @Override
                                public String getRouter() {
                                    return EisGoodWorldList.class.getSimpleName();

                                }
                            };


                            mainHomeList.add(tem);
                        }

                        Collections.sort(mainHomeList, (arg0, arg1) -> arg0.getRouter().compareTo(arg1.getRouter()));
                        crazyList.getAdapter().notifyDataSetChanged();


                    }
                });

        RetrofitClient.getClient().create(AdService.class).goodLastList()
                .subscribeOn(Schedulers.newThread())
                .observeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BOb<GoodLoveList>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        L.d("hcia", "e:" + e);

                    }

                    @Override
                    public void onNext(BOb<GoodLoveList> bannerListBOb) {


                        List<Product> ddd = bannerListBOb.getBody().getProLists();

                        HomeItemsBean tem = new HomeItemsBean<List<Product>>() {

                            @Override
                            public List<Product> getItem() {
                                return ddd;
                            }

                            @Override
                            public String getRouter() {
                                return FisGoodLastList.class.getSimpleName();

                            }
                        };


                        mainHomeList.add(tem);
                        Collections.sort(mainHomeList, (arg0, arg1) -> arg0.getRouter().compareTo(arg1.getRouter()));
                        crazyList.getAdapter().notifyDataSetChanged();


                    }
                });
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        requestData();


    }


    /**
     * Reselected Tab
     */
    @Subscribe
    public void onTabSelectedEvent(TabSelectedEvent event) {
//        L.d("hcia","event:"+event.position);
        if (event.position != MainFragment.FIRST) return;

        if (disFronTop == 0) {
//            mRefreshLayout.setRefreshing(true);
//            onRefresh();
        } else {
//            scrollView.setFocusable(true);
//            scrollView.setFocusableInTouchMode(true);
//            scrollView.smoothScrollTo(0, 0);
//            scrollView.postDelayed(new Runnable() {
//                @Override
//                public void run() {
//
//                    scrollView.fullScroll(View.FOCUS_UP);//类似于手动拖回顶部,有滚动过程
////                    scrollView.smoothScrollTo(0,0);
//                }
//            }, 100);

        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
//        L.d("hcia", "onDestroyView:");

        EventBusActivityScope.getDefault(_mActivity).unregister(this);
        unbinder.unbind();
    }


    @Override
    public void onPause() {
        super.onPause();
    }
}
